﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using WpfDemo.Common;
using WpfDemo.IRepository.Sys;
using WpfDemo.Models.Context;
using WpfDemo.Models.Sys;

namespace WpfDemo.Repository.Sys
{
    public class UserRepository : BaseRepository<UserEntity>, IUserRepository
    {

        
         IRoleRepository _RoleRepository;
        public UserRepository(EfContext db, IRoleRepository RoleRepository) : base(db)
        {
            _RoleRepository = RoleRepository;
        }

        public List<UserEntity> GetPageList<TKey>(PageInfo page, Expression<Func<UserEntity, bool>> whereLambda, Expression<Func<UserEntity, TKey>> orderBy, bool isAsc = true)
        {
            var query = from a in this.Query()
                        join b in _RoleRepository.Query() on a.F_RoleId equals b.F_Id into userRole
                        from ur in userRole.DefaultIfEmpty()
                        select new UserEntity()
                        {
                            F_Id = a.F_Id,
                            F_CreateTime = a.F_CreateTime,
                            F_Email = a.F_Email,
                            F_IsDisabled = a.F_IsDisabled,
                            F_Name = a.F_Name,
                            F_Password = a.F_Password,
                            F_Phone = a.F_Phone,
                            F_Remark = a.F_Remark,
                            F_RoleId = a.F_RoleId,
                            F_UserName = a.F_UserName,
                            F_RoleName = ur.F_Name,
                        };
            if (whereLambda != null)
            {
                query = query.Where(whereLambda);
            }
            var data = isAsc ?query.OrderBy(orderBy) :query.OrderByDescending(orderBy);
            
            var cnt = data.Count();
            page.TotalCount = cnt;
            return data.Skip((page.pageIndex - 1) * page.pageSize).Take(page.pageSize).ToList();
        }
    }
}
